// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.entity.ShipPlans;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.ShipPlansMapper;
import com.fowo.api.mapper.ShipPlansSubMapper;
import com.fowo.api.model.ship.plans.ShipPlansItemVo;
import com.fowo.api.model.ship.plans.ShipPlansPrintCompositeShipmentPlanTemplateAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintFNSKUBarcodeCustomAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintFNSKUBarcodeOldAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintFNSKUBarcodeTemplateAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintRegularShipmentPlanTemplateAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintRegularShippingScheduleAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintTheCombinedShipmentPlanAction;
import com.fowo.api.model.ship.plans.ShipPlansPrintTheOdaiLabelAction;
import com.fowo.api.model.ship.plans.ShipPlansSearchParamPo;
import com.fowo.api.model.ship.plans.ShipPlansVo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubItemVo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubItemVoPages;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubSearchParamPo;
import com.fowo.api.service.ShipPlansService;
import com.fowo.api.service.ShipPlansSubService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发货计划单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：杨志贤，沈友谅
 */
@Slf4j
@DataObjectType(ShipPlans.class)
@DS("ds24")
public class ShipPlansBaseServiceImpl
  extends ServiceImpl<ShipPlansMapper, ShipPlans>
  implements ShipPlansService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("shopIdShopName", "si.`shop_name`");
      put("createUserName", "su.`name`");
    }
  };

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ShipPlansService self;

  @Resource
  protected ShipPlansSubService shipPlansSubService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected ShipPlansPrintFNSKUBarcodeOldAction shipPlansPrintFNSKUBarcodeOldAction;

  @Autowired(required = false)
  protected ShipPlansPrintFNSKUBarcodeCustomAction shipPlansPrintFNSKUBarcodeCustomAction;

  @Autowired(required = false)
  protected ShipPlansPrintFNSKUBarcodeTemplateAction shipPlansPrintFNSKUBarcodeTemplateAction;

  @Autowired(required = false)
  protected ShipPlansPrintTheOdaiLabelAction shipPlansPrintTheOdaiLabelAction;

  @Autowired(required = false)
  protected ShipPlansPrintRegularShippingScheduleAction shipPlansPrintRegularShippingScheduleAction;

  @Autowired(required = false)
  protected ShipPlansPrintTheCombinedShipmentPlanAction shipPlansPrintTheCombinedShipmentPlanAction;

  @Autowired(required = false)
  protected ShipPlansPrintRegularShipmentPlanTemplateAction shipPlansPrintRegularShipmentPlanTemplateAction;

  @Autowired(required = false)
  protected ShipPlansPrintCompositeShipmentPlanTemplateAction shipPlansPrintCompositeShipmentPlanTemplateAction;

  @Resource
  protected Validator validator;

  /**
   * 创建发货计划单
   * @param model 发货计划单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ShipPlansVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ShipPlans entity = new ShipPlans();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getWarehouseType() == null) {
      entity.setWarehouseType("0");
    }

    if (model.getStatus() == null) {
      entity.setStatus("1");
    }

    if (model.getQuantity() == null) {
      entity.setQuantity(0L);
    }

    if (model.getCbm() == null) {
      entity.setCbm(new BigDecimal("0"));
    }

    if (model.getVolumeweight() == null) {
      entity.setVolumeweight(new BigDecimal("0"));
    }

    if (model.getItemweight() == null) {
      entity.setItemweight(new BigDecimal("0"));
    }

    if (model.getItemgrossweight() == null) {
      entity.setItemgrossweight(new BigDecimal("0"));
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getCreateBatchNumber())) {
      entity.setCreateBatchNumber(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "ShipPlans.createBatchNumber")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("发货计划单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 发货计划单
   */
  protected void updateAllChilds(ShipPlansVo model) throws Exception {
    if (model.getProductList() != null) {
      shipPlansSubService.saveAllByParentShipPlans(
        model.getId(),
        model.getProductList()
      );
    }
  }

  /**
   * 更新发货计划单
   * @param model 发货计划单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ShipPlansVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ShipPlans entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货计划单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "warehouseType",
      "createUser",
      "createTime",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新发货计划单（带空值）
   * @param model 发货计划单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ShipPlansVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ShipPlans entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货计划单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(
        model.getFiles() != null,
        ShipPlans::getFiles,
        JSON.toJSONString(model.getFiles())
      )
      .setSql(model.getFiles() == null, "files = null")
      .set(ShipPlans::getRemarks, model.getRemarks())
      .set(ShipPlans::getLastUpdateTime, model.getLastUpdateTime())
      .set(ShipPlans::getLastUpdateUser, model.getLastUpdateUser())
      .eq(ShipPlans::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ShipPlansSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 商品列表(productList) 对应的对象
    ShipPlansSubSearchParamPo productListSearchParam =
      new ShipPlansSubSearchParamPo();
    productListSearchParam.setDisableDataPremissions(true);
    productListSearchParam.setParentShipPlansInList(ids);
    ShipPlansSubMapper localShipPlansSubMapper = ContextHolder
      .getApplicationContext()
      .getBean(ShipPlansSubMapper.class);
    productListSearchParam.applySqlSegments();
    List<Long> productListIdList = localShipPlansSubMapper.searchIds(
      productListSearchParam
    );
    if (!productListIdList.isEmpty()) {
      ShipPlansSubService localShipPlansSubService = ContextHolder
        .getApplicationContext()
        .getBean(ShipPlansSubService.class);
      localShipPlansSubService.batchDelete(productListIdList);
    }
  }

  /**
   * 删除发货计划单
   * @param id 发货计划单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除发货计划单
   * @param ids 发货计划单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 通过创建批次号查询发货计划单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByCreateBatchNumber(String createBatchNumber) {
    return this.baseMapper.getIdByCreateBatchNumber(createBatchNumber);
  }

  /**
   * 通过创建批次号查询发货计划单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByCreateBatchNumber(List<String> list) {
    return this.baseMapper.getIdsByCreateBatchNumber(list);
  }

  /**
   * 通过发货计划单主键查询创建批次号
   */
  @Override
  public String getCreateBatchNumberById(Long id) {
    return this.baseMapper.getCreateBatchNumberById(id);
  }

  /**
   * 通过发货计划单主键查询创建批次号列表
   */
  @Override
  public List<String> getCreateBatchNumberByIds(List<Long> ids) {
    List<Map<String, Object>> maps =
      this.baseMapper.getCreateBatchNumberByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap ->
            (String) stringObjectMap.get("createBatchNumber")
          )
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 发货计划单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ShipPlansVo getVoById(Long id) throws Exception {
    ShipPlansVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    ShipPlansSubSearchParamPo productListSearchParamPo =
      new ShipPlansSubSearchParamPo();
    productListSearchParamPo.setParentShipPlans(id);
    productListSearchParamPo.getExtendData().put("queryMode", "sub");
    productListSearchParamPo.getExtendData().put("queryParent", "ShipPlans");
    productListSearchParamPo.applySqlSegments();
    vo.setProductList(shipPlansSubService.search(productListSearchParamPo));

    return vo;
  }

  /**
   * 分页查询发货计划单
   * @param search 查询条件
   * @return 发货计划单分页查询结果
   */
  @Override
  public Page<ShipPlansItemVo> pageSearch(ShipPlansSearchParamPo search) {
    Page<ShipPlansItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ShipPlansItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<ShipPlansItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<ShipPlansItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    ShipPlansSubSearchParamPo productListSearchParamPo =
      new ShipPlansSubSearchParamPo();
    productListSearchParamPo.setSort(sort);
    productListSearchParamPo.setPageSize(200);
    productListSearchParamPo.setParentShipPlansInList(
      pageResult
        .getRecords()
        .stream()
        .map(ShipPlansItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<ShipPlansSubItemVoPages>> productListMaps =
      shipPlansSubService.pagesByParentShipPlans(productListSearchParamPo);

    for (ShipPlansItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "productList",
        productListMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货计划单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(ShipPlansSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    ShipPlansSearchParamPo search
  ) {
    ShipPlansSearchParamPo parentSearchParam = new ShipPlansSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<ShipPlansItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      ShipPlansItemVo itemVo = parentList.get(0);

      ShipPlansSubSearchParamPo productListSearchParamPo =
        new ShipPlansSubSearchParamPo();
      productListSearchParamPo.setPageSize(search.getPageSize());
      productListSearchParamPo.setCurrent(search.getCurrent());
      productListSearchParamPo.setParentShipPlans(itemVo.getId());
      return shipPlansSubService.pageSearch(productListSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 发货计划单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ShipPlansOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<ShipPlansItemVo>> searchOptions(
    ShipPlansSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询发货计划单
   * @param search 查询条件
   * @return 发货计划单列表查询结果
   */
  @Override
  public List<ShipPlansItemVo> search(ShipPlansSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询发货计划单最后更新时间
   * @param search 查询条件
   * @return 发货计划单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ShipPlansSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 打印FNSKU条码（旧）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印FNSKU条码（旧）操作"
  )
  @Override
  public void printFNSKUBarcodeOld(List<Long> ids) throws Exception {
    if (shipPlansPrintFNSKUBarcodeOldAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintFNSKUBarcodeOldAction.run(ids);
  }

  /**
   * 打印FNSKU条码（自定义）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印FNSKU条码（自定义）操作"
  )
  @Override
  public void printFNSKUBarcodeCustom(List<Long> ids) throws Exception {
    if (shipPlansPrintFNSKUBarcodeCustomAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintFNSKUBarcodeCustomAction.run(ids);
  }

  /**
   * 打印FNSKU条码（模板）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印FNSKU条码（模板）操作"
  )
  @Override
  public void printFNSKUBarcodeTemplate(List<Long> ids) throws Exception {
    if (shipPlansPrintFNSKUBarcodeTemplateAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintFNSKUBarcodeTemplateAction.run(ids);
  }

  /**
   * 打印欧代标签
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印欧代标签操作"
  )
  @Override
  public void printTheOdaiLabel(List<Long> ids) throws Exception {
    if (shipPlansPrintTheOdaiLabelAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintTheOdaiLabelAction.run(ids);
  }

  /**
   * 打印常规发货计划
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印常规发货计划操作"
  )
  @Override
  public void printRegularShippingSchedule(List<Long> ids) throws Exception {
    if (shipPlansPrintRegularShippingScheduleAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintRegularShippingScheduleAction.run(ids);
  }

  /**
   * 打印组合发货计划
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印组合发货计划操作"
  )
  @Override
  public void printTheCombinedShipmentPlan(List<Long> ids) throws Exception {
    if (shipPlansPrintTheCombinedShipmentPlanAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintTheCombinedShipmentPlanAction.run(ids);
  }

  /**
   * 打印常规发货计划（模板）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印常规发货计划（模板）操作"
  )
  @Override
  public void printRegularShipmentPlanTemplate(List<Long> ids)
    throws Exception {
    if (shipPlansPrintRegularShipmentPlanTemplateAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintRegularShipmentPlanTemplateAction.run(ids);
  }

  /**
   * 打印组合发货计划（模板）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印组合发货计划（模板）操作"
  )
  @Override
  public void printCompositeShipmentPlanTemplate(List<Long> ids)
    throws Exception {
    if (shipPlansPrintCompositeShipmentPlanTemplateAction == null) {
      throw new Exception("此操作当前不可用");
    }
    shipPlansPrintCompositeShipmentPlanTemplateAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    ShipPlansSearchParamPo search = new ShipPlansSearchParamPo();
    return MapUtil
      .builder()
      .put("Entire", this.baseMapper.entireCount(search))
      .put("Pending", this.baseMapper.pendingCount(search))
      .put("Processed", this.baseMapper.processedCount(search))
      .put("JNJ", this.baseMapper.jNJCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<ShipPlansItemVo> entire(ShipPlansSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.entire(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<ShipPlansItemVo> entirePage(ShipPlansSearchParamPo search) {
    Page<ShipPlansItemVo> entirePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return entirePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return entirePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    entirePage =
      this.baseMapper.entirePage(
          search.toPage(this.baseMapper.entireCount(search)),
          search
        );
    List<Long> recordIds = entirePage
      .getRecords()
      .stream()
      .map(ShipPlansItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return entirePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return entirePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    entirePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return entirePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货计划单分页查询结果
   */
  @Override
  public Page<?> entirePageWithChildSearch(ShipPlansSearchParamPo search) {
    return appendWithChild(
      entirePage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date entireLastUpdateTime(ShipPlansSearchParamPo search) {
    return this.baseMapper.entireLastUpdateTime(search);
  }

  /**
   * 待处理
   */
  @Override
  public List<ShipPlansItemVo> pending(ShipPlansSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.pending(search);
  }

  /**
   * 待处理分页
   */
  @Override
  public Page<ShipPlansItemVo> pendingPage(ShipPlansSearchParamPo search) {
    Page<ShipPlansItemVo> pendingPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return pendingPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return pendingPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    pendingPage =
      this.baseMapper.pendingPage(
          search.toPage(this.baseMapper.pendingCount(search)),
          search
        );
    List<Long> recordIds = pendingPage
      .getRecords()
      .stream()
      .map(ShipPlansItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return pendingPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return pendingPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    pendingPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return pendingPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货计划单分页查询结果
   */
  @Override
  public Page<?> pendingPageWithChildSearch(ShipPlansSearchParamPo search) {
    return appendWithChild(
      pendingPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询待处理最后更新时间
   * @param search 查询条件
   * @return 待处理最后更新时间
   */
  @Override
  public Date pendingLastUpdateTime(ShipPlansSearchParamPo search) {
    return this.baseMapper.pendingLastUpdateTime(search);
  }

  /**
   * 已处理
   */
  @Override
  public List<ShipPlansItemVo> processed(ShipPlansSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.processed(search);
  }

  /**
   * 已处理分页
   */
  @Override
  public Page<ShipPlansItemVo> processedPage(ShipPlansSearchParamPo search) {
    Page<ShipPlansItemVo> processedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return processedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return processedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    processedPage =
      this.baseMapper.processedPage(
          search.toPage(this.baseMapper.processedCount(search)),
          search
        );
    List<Long> recordIds = processedPage
      .getRecords()
      .stream()
      .map(ShipPlansItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return processedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return processedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    processedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return processedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货计划单分页查询结果
   */
  @Override
  public Page<?> processedPageWithChildSearch(ShipPlansSearchParamPo search) {
    return appendWithChild(
      processedPage(search),
      search.toChildSort("productList")
    );
  }

  /**
   * 查询已处理最后更新时间
   * @param search 查询条件
   * @return 已处理最后更新时间
   */
  @Override
  public Date processedLastUpdateTime(ShipPlansSearchParamPo search) {
    return this.baseMapper.processedLastUpdateTime(search);
  }

  /**
   * 已驳回
   */
  @Override
  public List<ShipPlansItemVo> jNJ(ShipPlansSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.jNJ(search);
  }

  /**
   * 已驳回分页
   */
  @Override
  public Page<ShipPlansItemVo> jNJPage(ShipPlansSearchParamPo search) {
    Page<ShipPlansItemVo> jNJPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return jNJPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return jNJPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    jNJPage =
      this.baseMapper.jNJPage(
          search.toPage(this.baseMapper.jNJCount(search)),
          search
        );
    List<Long> recordIds = jNJPage
      .getRecords()
      .stream()
      .map(ShipPlansItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return jNJPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return jNJPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    jNJPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return jNJPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 发货计划单分页查询结果
   */
  @Override
  public Page<?> jNJPageWithChildSearch(ShipPlansSearchParamPo search) {
    return appendWithChild(jNJPage(search), search.toChildSort("productList"));
  }

  /**
   * 查询已驳回最后更新时间
   * @param search 查询条件
   * @return 已驳回最后更新时间
   */
  @Override
  public Date jNJLastUpdateTime(ShipPlansSearchParamPo search) {
    return this.baseMapper.jNJLastUpdateTime(search);
  }
}
